import React, { Component } from 'react';
import {connect} from 'react-redux';
import {put} from 'redux-saga/effects';
class Home extends Component {
    state={
        // 商品列表数组
        goodsList:[],
        goodsname:'',
        price:''
    }
    UNSAFE_componentWillMount(){
       // 请求商品列表数据
       this.props.dispatch({type:'goods/init/async'});
    }

    submit(){
        if(this.state.goodsname===''){
            return alert('请输入商品名称');
        }
        if(this.state.price===''){
            return alert('请输入商品价格');
        }
        const {goodsname,price}=this.state;
        const action={
            type:'goods/add',
            payload:{goodsname,price}
        }
        this.props.dispatch(action);
        // 重置表单
        this.setState({goodsname:'',price:''});
    }
    render() {
        return (
            <div style={{width:800,margin:'auto'}}>
                <h1>商品列表</h1>
                <div style={{background:'#F2F2F2',padding:10,margin:'10px 0'}}>

                    <input value={this.state.goodsname} onChange={e=>this.setState({goodsname:e.target.value})} type="text" placeholder='商品名称'/>
                    <input value={this.state.price} onChange={e=>this.setState({price:e.target.value})} type="text" placeholder='商品价格'/>
                    <button onClick={()=>this.submit()}>添加</button>

                </div>
                <table width="800" border="1">
                    <thead>
                        <tr>
                            <th>id</th>
                            <th>商品名称</th>
                            <th>商品价格</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {
                            this.props.goodsList.map((item,index)=>(
                                <tr key={item.id}>
                                    <td>{item.id}</td>
                                    <td>{item.goodsname}</td>
                                    <td>{item.price}</td>
                                    <td>
                                        <button onClick={()=>this.del(index)}>删除</button>
                                    </td>
                                </tr>
                            ))
                        }
                    </tbody>
                </table>
            </div>
        )
    }
    // 删除商品
    del(index){
        // 数据操作对象action
        const action={
            // 操作类型, 需要个reducer函数中的case对应
            type:'goods/remove',
            // 操作数据需要的参数
            payload:index
        }
        // 通过store.dispatch()调用reducer函数, 实现状态数据更新
        this.props.dispatch(action);
    }
}

export default connect(state=>({
    goodsList:state.goodsList
}))(Home);
